
import{ checkFileSize  } from 'web-plugin-tool'
import { ElMessage } from 'element-plus'

// 替代input上传
/**
 * 替代input上传
 * @param size - 可选，文件大小限制 单位M，默认10000M
 * @param accept - 允许上传的文件类型
 * @param onFile - 文件选择后的回调函数，接收选中的文件对象
 */
export function handleUpload({
	size = 10000,
	accept,
	onFile,
}: {
	size?: number
	accept: string
	onFile: (file: File) => void
}) {

	const input = document.createElement('input')
	input.type = 'file'
	input.accept = accept
	input.click()
	input.addEventListener('change', (e: any) => {

		const f = e.target.files[0]
		if (!checkFileSize(f.size, size)) {
			ElMessage.error(`文件过大, 限制大小为${size}M`)
			// alert('文件过大')
			return
		}
		onFile(f)
	})
}

/**
 * 获取当前星期几
 *
 */
export function getWeekDate() {
	var date = new Date()
	var day = date.getDay()
	let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
	return weeks[day]
}

/**
 * 移除对象中的空属性
 * @param obj {xxx: '',bbb:''}
 */
export function removeObjNullValue(obj: any): any {
	let tem: Record<string, any> = {}
	for (const item in obj) {
		if (obj[item]) {
			tem[item] = obj[item]
		}
	}
	return tem
}

export function startsWithNumberOrDecimal(str: string) {
	return /^[0-9]+ /.test(str) || /^[0-9.]+ /.test(str)
}

export function endsWithChinese(str: string) {
	return /[\u4e00-\u9fff]+$/.test(str)
}

// 合并数据
export function mergeData(list: any[]) {
	const attr = 'type'
	function mergedByName(arr: any[]) {
		let merged: any = {}
		arr.forEach((item) => {
			delete item.children
			const name = item.name
			if (merged[name]) {
				merged[name].number += item.number
			} else {
				merged[name] = { ...item }
			}
		})
		return Object.values(merged)
	}
	const data = list.reduce((acc, item) => {
		if (!acc[item[attr]]) {
			acc[item[attr]] = { ...item } // 初始化当前id的对象
		} else {
			if (!Array.isArray(acc[item[attr]].children)) {
				acc[item[attr]].children = [acc[item[attr]]]
			}
			acc[item[attr]] = {
				...acc[item[attr]],
				...item,
				// children: [...acc[item[attr]].children, item],
				children: mergedByName([...acc[item[attr]].children, item]),
			} // 合并对象
		}
		return acc
	}, {})
	return Object.values(data)
}

// 去除所有的空格
export function removeSpaces(str: string) {
	return String(str).replace(/\s+/g, '')
}

// 滚动到指定元素
export function scrollIntoView(el: Element) {
	if (!el || !el.scrollIntoView) return
	el.scrollIntoView({
		behavior: 'smooth',
		block: 'center',
	})
}

// 去除前后空格后对比两个字符串是否相等
export function compareString(str: string, target: string) {
	return (str + '').trim() === (target + '').trim()
}

// 把table的数据转换为数组.处理了合并单元格的场景
export function tableToObjectArray(table: Element) {
	const rows = table.querySelectorAll('tr')
	const result: any[] = []
	const colSpanInfo: any[] = []

	rows.forEach((row, rowIndex) => {
		const cells = row.querySelectorAll('td, th')
		const rowData: any = {}
		let colIndex = 0

		cells.forEach((cell: any) => {
			// 处理合并单元格
			while (colSpanInfo[colIndex] && colSpanInfo[colIndex].remainingRows > 0) {
				const info = colSpanInfo[colIndex]
				rowData[`col${colIndex}`] = info.value
				info.remainingRows--
				colIndex++
			}

			const cellValue = cell.textContent.trim()
			const rowSpan = parseInt(cell.getAttribute('rowspan') || 1, 10)
			const colSpan = parseInt(cell.getAttribute('colspan') || 1, 10)

			for (let i = 0; i < colSpan; i++) {
				rowData[`col${colIndex}`] = cellValue
				if (rowSpan > 1) {
					colSpanInfo[colIndex] = {
						value: cellValue,
						remainingRows: rowSpan - 1,
					}
				}
				colIndex++
			}
		})

		// 处理剩余的合并单元格
		while (colIndex < colSpanInfo.length) {
			if (colSpanInfo[colIndex] && colSpanInfo[colIndex].remainingRows > 0) {
				const info = colSpanInfo[colIndex]
				rowData[`col${colIndex}`] = info.value
				info.remainingRows--
			}
			colIndex++
		}

		result.push({
			...rowData,
			el: row,
		})
	})
	return result
}

export function tableRowSpanToList(table: any) {
	const rows = Array.from(table.rows)
	const resMap: any = {}
	rows.forEach((r: any, index) => {
		const td = r.querySelectorAll('td')
		let num = 0
		for (let i = 0; i < td.length; i++) {
			const d = td[i]
			const rowSpan = parseInt(d.getAttribute('rowspan') || 0, 10)
			if (rowSpan > 0) {
				num = rowSpan
			}
		}
		if (num <= 0) {
			return
		} // 第0个就是合并其他列的tr
		const res = rows.slice(index, index + num)
		resMap[index] = res
	})
	return resMap
}

// 拆分合并的表格，并返回拆好的表格
export function splitMergedCells(tableEl: any) {
	const t = tableEl
	const table = t.cloneNode(true)
	table.id = 'new_table'
	table.style.display = 'none'
	table.style.width = 0
	table.style.height = 0
	document.body.appendChild(table)
	const rows = table.rows
	const cellTracker: any[] = []
	// 初始化 cellTracker 数组，用于标记单元格是否已处理
	for (let i = 0; i < rows.length; i++) {
		cellTracker[i] = []
		for (let j = 0; j < rows[i].cells.length; j++) {
			cellTracker[i][j] = false
		}
	}

	// 遍历表格的每一行
	for (let i = 0; i < rows.length; i++) {
		const row = rows[i]
		// 遍历当前行的每个单元格
		for (let j = 0; j < row.cells.length; j++) {
			const cell = row.cells[j]
			if (!cellTracker[i][j]) {
				const rowSpan = cell.rowSpan || 1
				const colSpan = cell.colSpan || 1
				const cellContent = cell.textContent

				// 重置 rowspan 和 colspan
				cell.rowSpan = 1
				cell.colSpan = 1

				// 填充拆分后的单元格
				for (let r = 0; r < rowSpan; r++) {
					for (let c = 0; c < colSpan; c++) {
						if (r === 0 && c === 0) {
							// 第一个单元格保持原有内容
							cell.textContent = cellContent
						} else {
							const newRow = i + r
							const newCol = j + c

							if (newRow >= rows.length) {
								table.insertRow()
							}

							const newCell = table.rows[newRow].insertCell(newCol)
							newCell.textContent = cellContent
						}
						cellTracker[i + r][j + c] = true
					}
				}
			}
		}
	}
	const newTable = document.querySelector('#new_table')
	document.body.removeChild(table)
	return newTable
}

// 获取原始表格中的合并行和当前行
export function getRowanTable({ mergeTable, splitTable, hgxData }: { mergeTable: any; splitTable: any; hgxData: any }) {
	const rowList = splitTable.rows || []
	// console.log(rowList, 'rowList')
	const { steerKey, meanValue, projectMetricKey, indicatorName } = hgxData
	let data = {
		index: -1,
		tr: null,
	}

	// 在拆分的表格中查找对应的行和索引值
	for (let i = 0; i < rowList.length; i++) {
		const tr = rowList[i]
		const text = tr.innerText.replace(/\s+/g, '')
		if (
			text.includes(indicatorName) &&
			text.includes(steerKey) &&
			text.includes(meanValue) &&
			text.includes(projectMetricKey)
		) {
			// console.log(tr, 'tr', mergeTable.rows[i]);
			data.index = i
			data.tr = mergeTable.rows[i]
		}
	}
	if (data.index === -1) return {}

	const mergeTableRowList = Array.from(mergeTable.rows).slice(0, data.index)
	let rowspanTr = null
	// 找到数组中最后一个带列合并的tr
	for (let i = mergeTableRowList.length - 1; i >= 0; i--) {
		const r: any = mergeTableRowList[i]
		if (r.innerHTML.includes('rowspan')) {
			rowspanTr = r
			// console.log(r.innerText.replace(/\s+/g, ''));
			break
		}
	}

	return {
		rowspanTr, // 合并的行tr
		splitTr: Array.from(mergeTable.rows)[data.index], // 当前行tr
	}
}

// 截取字符串后面的单位,字符串中间的不管
export function extractTrailingUnit(str: string) {
	// 从字符串末尾开始匹配非数字字符
	const match = str.match(/[^0-9]+$/)
	return match ? match[0] : ''
}

export function removeParenthesesContent(text: string) {
  // 正则表达式匹配中文和英文括号及其内容
  return text.replace(/\([^()]*\)|（[^（）]*）|【[^【】]*】|「[^「」]*」/g, '').trim()
}

/**
 * 提取字符串中最外层括号内的内容
 * @param {string} str - 要处理的字符串
 * @returns {string|null} 返回括号内的内容，如果没有匹配则返回空字符串
 */
export function extractOuterParentheses(str: string) {
  const res:any = str.match(/[（(]([^）)]*)[）)]/)
  if(res?.length>0){
    return res[1]
  }
  return ''
}

/**
 * 根据百分比生成颜色值
 */
export function generateColorByPercentage(percentage: number) {
  // 将百分比转换为 0 到 255 之间的值
  const red = Math.round(percentage * 2.555);
  const green = 255 - red;
  const blue = 0;
  return `rgb(${red}, ${green}, ${blue})`;
}